/************************************
*  Copyright (C) 2010 Julien MOTTIN.
*  Contact: julien.mottin@gueydan.eu
*
*  This file is part of Gueydan.
*
*  Gueydan is free software: you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation, either version 3 of the License, or
*  (at your option) any later version.
*
*  Gueydan is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  You should have received a copy of the GNU General Public License
*  along with Gueydan.  If not, see <http://www.gnu.org/licenses/>.
*
*************************************/
// Local
// Local
#include "util.h"

// QtCore
#include <QString>
#include <QDir>
#include <QFileInfoList>

// Standard libraries
#include <math.h>

void StringToUnit(const QString &iString, double &oValue, QString &oUnit)
{
    // Init
    oValue = 0.0;
    oUnit = "";

    // Sequential Search...
    double tmpVal = 0.0;
    bool ok = false;
    QString tmpString;
    int size = iString.size();
    for (int i=0;i<size;i++)
    {        
        tmpString = iString;
        tmpString.chop(i);
        tmpVal = tmpString.toDouble(&ok);
        if (ok)
        {
            oValue = tmpVal;
            oUnit = iString.right(i).simplified().toLower();
            break;
        }
    }
}

bool ComparePrecision(double Val1, double Val2, double Precision)
{
    return (fabs(Val1-Val2)<=fabs(Precision));
}

void RecursiveRemove(const QString &iDirectoryPath)
{
    QDir zeDir(iDirectoryPath);
    QFileInfoList Entries = zeDir.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
    QFileInfoList::const_iterator iter = Entries.constBegin();
    while (iter!=Entries.constEnd())
    {
        QFileInfo curInfo = *iter;

        // Case dir => recursive call
        if (curInfo.isDir())
            RecursiveRemove(curInfo.filePath());

        else if (curInfo.isFile())
            QFile::remove(curInfo.filePath());

        // Iterate
        iter++;
    }

    // Remove input dir
    QString zeDirName = zeDir.dirName();
    zeDir.cdUp();
    zeDir.rmdir(zeDirName);
}
